<?php


namespace app\api\controller;


use app\common\controller\WeChat;
use think\Controller;
use think\Db;
use think\Exception;
use think\Session;
use think\Validate;

class Index extends Controller
{

    public function personFace(){
        $commonDevice = new Test();
        $token = $commonDevice->token();
        $employeeNo = $_GET['employeeNo'];
        $black = $commonDevice->personFace($employeeNo,$token);

        dump($black);
    }


    //
    public function updates(){
        //更新人脸
        $data['realName'] = "小支";
        $data['mobile'] = "15578984612";
        //像设备下发人员信息
        $nowtime = date("Y-m-d");
        $order = Db::name("tickets_order")->where(['name'=>$data['realName'],'mobile'=>$data['mobile']])->field("id")->select();
        $orderVal = [];
        foreach ($order as $item){
            $orderVal[] = $item['id'];
        }
        //查询已购买的门票
        $tickets_list = Db::name("tickets_list")->where(['order_id'=>['in',$orderVal],'end_time'=>['egt',$nowtime]])->field("signcode")->select();


        $commonDevice = new Test();
        foreach ($tickets_list as $k=>$v){
            $cardAdd['employeeNo'] = $v['signcode'];
            $cardAdd['faceImageBase64'] = $data['faceUrl'];
            $balck = $commonDevice->personsUpdate($cardAdd);
        }
    }

    //修改个人信息
    public function updateMain(){
        $common = new Common();
        $userid = $common->common();
        try{
            $rule = [
                ["realName", "require", "姓名不能为空"],
                ["idCard", "require", "身份证号不能为空"],
                ["mobile", "require", "手机号不能为空"],
//                ["faceUrl", "require", "人脸头像不能为空"],
            ];

            $validate = new Validate($rule);
            $data = $this->request->post();
            if (!$validate->check($data)) {
                throw new Exception($validate->getError());
            }

            if($data['faceid'] == 1){
                if(empty($data['faceUrl'])){
                    throw new Exception("人脸头像不能为空");
                }
            }

            foreach ($data as $k=>$v){
                if($v=="null"){
                    unset($data[$k]);
                }
            }
            $data['password'] = md5("123456");
            if(!empty($data['mobile'])){
                if(!$this->isMobile($data['mobile'])){
                    throw new Exception("手机号格式有误");
                }
            }
            if(!empty($data['idCard'])){
                if(!$this->setCard($data['idCard'])){
                    throw new Exception("身份证号格式有误");
                }
            }
            $data['register_ip'] = request()->ip();
            $data['sex'] = intval($data['sex'])+1;

            //判断该手机是否已进行实名操作
            $isMobile = Db::name("admin_fans")->where(['mobile'=>$data['mobile'],'id'=>['neq',$userid]])->find();
            if(!empty($isMobile)){
                throw new Exception("该手机号已注册");
            }
            //需要修改的地方

            $detaill = Db::name("admin_fans")->where(['id'=>$userid])->find();
            if(empty($detaill)){
                $data['addtime'] = time();
                Db::name("admin_fans")->insertGetId($data);
            }else{
                $data['updatetime'] = time();
                Db::name("admin_fans")->where(['id'=>$userid])->update($data);
            }
            $id = Db::name("admin_fans")->where(['id'=>$userid])->value("id");

            //更新人脸
            //像设备下发人员信息
            $nowtime = date("Y-m-d");
            $order = Db::name("tickets_order")->where(['name'=>$data['realName'],'mobile'=>$data['mobile']])->field("id")->select();
            $orderVal = [];
            foreach ($order as $item){
                $orderVal[] = $item['id'];
            }
            //查询已购买的门票
            $tickets_list = Db::name("tickets_list")->where(['order_id'=>['in',$orderVal],'end_time'=>['egt',$nowtime]])->field("signcode")->select();
            $commonDevice = new Test();
            foreach ($tickets_list as $k=>$v){
                $cardAdd['employeeNo'] = $v['signcode'];
                $cardAdd['faceImageBase64'] = $data['faceUrl'];
                $commonDevice->personsUpdate($cardAdd);
            }

            //记录操作日志
            $log['remark'] = "用户更新信息,用户ID【".$id."】";
            $log['operator'] = $userid;
            $log['operator_id'] = $id;
            $common->addLog($log);

            $black['code'] = 0;
            $black['msg'] = "操作成功";

            $black['code'] = 0;
            $black['userinfo'] = '';
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);
    }

    //获取微信公众号配置信息
    public function config()
    {
        $thisWechat = Session::get("thisWechat");
        $config = Db::name("config")->where(['id'=>$thisWechat['id']])->find();
        return $config;
    }

    //获取平台基本信息
    public function configApi(){
        $thisWechat = Session::get("thisWechat");
        $data = Db::name("config")->where(['id'=>$thisWechat['id']])->find();
        $data['qr_code'] = "http://".$_SERVER['HTTP_HOST'].$data['qr_code'];
        $black['code'] = 0;
        $black['data'] = $data;
        return json_encode($black);
    }


    //验证手机格式
    function isMobile($mobile) {
        if (!is_numeric($mobile)) {
            return false;
        }
        return preg_match('#^1[3,4,5,6,7,8,9]{1}[\d]{9}$#', $mobile) ? true : false;
    }

    //验证身份证
    public static function setCard($card)
    {
        $city = [11 => "北京", 12 => "天津", 13 => "河北", 14 => "山西", 15 => "内蒙古", 21 => "辽宁", 22 => "吉林", 23 => "黑龙江 ", 31 => "上海", 32 => "江苏", 33 => "浙江", 34 => "安徽", 35 => "福建", 36 => "江西", 37 => "山东", 41 => "河南", 42 => "湖北 ", 43 => "湖南", 44 => "广东", 45 => "广西", 46 => "海南", 50 => "重庆", 51 => "四川", 52 => "贵州", 53 => "云南", 54 => "西藏 ", 61 => "陕西", 62 => "甘肃", 63 => "青海", 64 => "宁夏", 65 => "新疆", 71 => "台湾", 81 => "香港", 82 => "澳门", 91 => "国外 "];
        $tip = "";
        $match = "/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/";
        $pass = true;
        if (!$card || !preg_match($match, $card)) {
            //身份证格式错误
            $pass = false;
        } else if (!$city[substr($card, 0, 2)]) {
            //地址错误
            $pass = false;
        } else {
            //18位身份证需要验证最后一位校验位

            if (strlen($card) == 18) {
                $card = str_split($card);
                //∑(ai×Wi)(mod 11)
                //加权因子
                $factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                //校验位
                $parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
                $sum = 0;
                $ai = 0;
                $wi = 0;
                for ($i = 0; $i < 17; $i++) {
                    $ai = $card[$i];
                    $wi = $factor[$i];
                    $sum += $ai * $wi;
                }
                $last = $parity[$sum % 11];
                if ($parity[$sum % 11] != $card[17]) {
//                        $tip = "校验位错误";
                    $pass = false;
                }
            } else {
                $pass = false;
            }
        }
        if (!$pass) return false;/* 身份证格式错误*/
        return true;/* 身份证格式正确*/
    }


    public function uploads($data){
        //$logo_data = $this->request->post('logo_base64','');
        $logo_data = $data;
        if(!empty($logo_data)){
            //$data = file_get_contents('./1.txt');
            $reg = '/data:image\/(\w+?);base64,(.+)$/si';
            preg_match($reg,$logo_data,$match_result);
            $file_name = time().'.'.$match_result[1];
            $logo_path = ROOT_PATH . 'public' . DS . 'upload/'.date("Ym").DS;
            if(!is_dir($logo_path))
            {
                is_file($logo_path) or mkdir($logo_path,0700);
            }
            $logo_path .=$file_name;
            $num = file_put_contents($logo_path,base64_decode($match_result[2]));
            if(!empty($num)){
                //上传成功之后，再进行缩放操作
                //$image = \think\Image::open($logo_path);
                // 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
                //$image->thumb(102, 36)->save($logo_path);
                return $file_name;
            }else{
                return false;
            }
        }else{
            return true;
        }
    }

    /**
     * 图片格式转换
     * @param string $image_path 文件路径或url
     * @param string $to_ext 待转格式，支持png,gif,jpeg,wbmp,webp,xbm
     * @param null|string $save_path 存储路径，null则返回二进制内容，string则返回true|false
     * @return boolean|string $save_path是null则返回二进制内容，是string则返回true|false
     * @throws Exception
     * @author klinson <klinson@163.com>
     */
    function transform_image($image_path, $to_ext = 'jpeg')
    {
        if (! in_array($to_ext, ['png', 'gif', 'jpeg', 'wbmp', 'webp', 'xbm','jpg'])) {
            throw new Exception('unsupport transform image to ' . $to_ext);
        }
        $common = new Common();
        //人脸检测
        //调用百度Api
        $res = $common->baiApi();
        if(empty($res['access_token'])){
            $image = ROOT_PATH . 'public' . DS . 'upload/'.date("Ym").DS.$image_path;
            unlink($image);
            throw new Exception("Api调用失败");
        }
        //检测人脸
        $images =  "https://".$_SERVER['HTTP_HOST'].'/upload/'.date("Ym").DS.$image_path;
        $bodys['image'] = $images;
        $bodys['image_type'] = "URL";
        $bodys['face_field'] = "faceshape,facetype";
        $bodys = json_encode($bodys);
        $fance = $common->fance($res['access_token'],$bodys);
        if(!empty($fance['error_code'])){
            $image = ROOT_PATH . 'public' . DS . 'upload/'.date("Ym").DS.$image_path;
            unlink($image);
            throw new Exception("请上传人脸头像");
        }
        $image_path = ROOT_PATH . 'public' . DS . 'upload/'.date("Ym").DS.$image_path;
        switch (exif_imagetype($image_path)) {
            case IMAGETYPE_GIF :
                $img = imagecreatefromgif($image_path);
                break;
            case IMAGETYPE_JPEG :
            case IMAGETYPE_JPEG2000:
                $img = imagecreatefromjpeg($image_path);
                break;
            case IMAGETYPE_PNG:
                $img = imagecreatefrompng($image_path);
                break;
            case IMAGETYPE_BMP:
            case IMAGETYPE_WBMP:
                $img = imagecreatefromwbmp($image_path);
                break;
            case IMAGETYPE_XBM:
                $img = imagecreatefromxbm($image_path);
                break;
            case IMAGETYPE_WEBP: //(从 PHP 7.1.0 开始支持)
                $img = imagecreatefromwebp($image_path);
                break;
            default :
                throw new \Exception('Invalid image type');
        }
        $function = 'image'.$to_ext;
        $imgname = uniqid().'.'.$to_ext;
        $tmp = ROOT_PATH . 'public' . DS . 'upload/'.date("Ym").'/'.$imgname;
        if ($function($img, $tmp)) {
            $content = file_get_contents($tmp);
            unlink($image_path); //删除原始图片
            return $imgname;
        } else {
            unlink($tmp);
            throw new \Exception('the file '.$tmp.' can not write');
        }
    }

}